package com.sj.data;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-07-25
 * Time: 上午 11:26
 * Description: 哈希表
 *
 * @author xiaoqi
 * @since 2022-07-25
 */
public class HashTab<T, D> {

    private NodeList<T, D>[] nodeList;
    private int size;

    public HashTab() {
        nodeList = new NodeList[10];
        for (int i = 0; i < nodeList.length; i++) {
            nodeList[i] = new NodeList<>();
        }
    }

    /**
     * 如果需要获取的键的值为null 那么返回一个默认值
     *
     * @param key   键
     * @param value 默认值
     * @return 返回值
     */
    public D getOrDefault(T key, D value) {
        return this.get(key) == null ? value : this.get(key);
    }

    /**
     * 存放键值对到HashTab
     *
     * @param key   键
     * @param value 值
     */
    public void put(T key, D value) {
        Node<T, D> node = new Node<>(key, value);
        boolean result = nodeList[hash(key.hashCode())].add(node);
        if (result) {
            size++;
        }
    }

    /**
     * 根据键删除
     *
     * @param key 键
     */
    public void remove(T key) {
        try {
            nodeList[hash(key.hashCode())].remove(key);
            size--;
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据键获取值
     *
     * @param key 键
     * @return 值
     */
    public D get(T key) {
        return nodeList[hash(key.hashCode())].get(key);
    }

    /**
     * 取余法控制下标
     *
     * @param code hash码
     * @return
     */
    private Integer hash(Integer code) {
        return code % 10;
    }

    public int getSize() {
        return size;
    }

}